﻿/**
 *    Copyright 2012 Yohan Courbe
 *
 *  Licensed under the Apache License, Version 2.0 (the "License")
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *      
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

using System;
using System.Net;
using PacketDotNet;

namespace NetworkAnalyzer.Engines.TcpSessionTracker
{
    internal class TcpSession
    {
        public readonly DateTime StartTime = DateTime.Now;
        public ApplicativeProtocol ApplicativeProtocol = ApplicativeProtocol.Unknown;
        public int DownloadBandwidth;
        public DateTime EndTime;
        public bool HasTimeout;
        public bool IsClosed;
        public bool IsInitByRemoteHost;
        public readonly IPAddress Localhost;
        public readonly ushort Localport;
        public int NumberOfPackets;
        public readonly IPAddress Remotehost;
        public readonly ushort Remoteport;
        public int UploadBandiwdth;
        public bool HasBeenSavedInDatabase;

        private const int MaxTtl = 300;
        private bool _alreadyStarted;
        private int _timeToLive = MaxTtl;

        public TcpSession(IPAddress localhost, ushort localport, IPAddress remotehost, ushort remoteport)
        {
            Localhost = localhost;
            Remotehost = remotehost;
            Localport = localport;
            Remoteport = remoteport;
        }

        private void CloseSession(bool hasTimeout)
        {
            HasTimeout = hasTimeout;
            IsClosed = true;

            EndTime = DateTime.Now;
            
            if (hasTimeout)
            {
                EndTime = EndTime.AddSeconds(-MaxTtl);
            }
        }

        private void ResetTimeout()
        {
            _timeToLive = MaxTtl; // Reset timetolive.
        }

        public void AddPacket(Packet packet, IpPacket ipPacket, TcpPacket tcpPacket)
        {
            ResetTimeout();
            NumberOfPackets++;

            var isLocalSource = ipPacket.SourceAddress.IsLocalHost();

            if (tcpPacket.Syn && !tcpPacket.Ack) // CLIENT TRIES TO ESTABLISH A NEW SESSION
            {
                if (_alreadyStarted)
                {
                    CloseSession(true);
                }

                _alreadyStarted = true;

                IsInitByRemoteHost = !isLocalSource;
            }

            if (tcpPacket.Fin)
            {
                CloseSession(false);
            }

            if (isLocalSource)
            {
                UploadBandiwdth += packet.Bytes.Length;
            }
            else
            {
                DownloadBandwidth += packet.Bytes.Length;
            }

            if (ApplicativeProtocol == ApplicativeProtocol.Unknown)
            {
                ApplicativeProtocol = Tools.GetApplicativeProtocolByPort(tcpPacket.SourcePort, tcpPacket.DestinationPort);
            }
        }

        public bool MatchSession(IPAddress localhost, ushort localport, IPAddress remotehost, ushort remoteport)
        {
            if (IsClosed)
            {
                return false;
            }

            if (!Equals(Localhost, localhost))
            {
                return false;
            }

            if (Localport != localport)
            {
                return false;
            }

            if (!Equals(Remotehost, remotehost))
            {
                return false;
            }

            if (Remoteport != remoteport)
            {
                return false;
            }

            return true;
        }

        public void DecreaseTtl()
        {
            if (_timeToLive <= 0 && !IsClosed)
            {
                CloseSession(true);
            }
            else
            {
                _timeToLive--;
            }
        }
    }
}